package com.safety.hat.service.impl.hat;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.safety.hat.data.ACTEnum;
import com.safety.hat.data.Result;
import com.safety.hat.data.hat.HatHeartInfoBO;
import com.safety.hat.service.hat.adapter.IHatSocketLocationAdapterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: lijun
 * @Date: 2020/5/24 23:35
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class HatSocketLocationAdapterServiceImpl implements IHatSocketLocationAdapterService<HatHeartInfoBO> {

    private static final ConcurrentHashMap<String, List<HatHeartInfoBO>> locationInfo = new ConcurrentHashMap<>(64);

    /**
     * 处理消息
     */
    @Override
    public void handleMessage(HatHeartInfoBO message, Session session) {
        List<HatHeartInfoBO> infoBOList = locationInfo.getOrDefault(message.getUserId(), Lists.newArrayList());
        message.setReportTime(new Date());
        if (infoBOList.size() > 0 && infoBOList.get(infoBOList.size() - 1).equalsSamePoint(message)) {
            infoBOList.remove(infoBOList.get(infoBOList.size() - 1));
        }
        infoBOList.add(message);
        locationInfo.put(message.getUserId(), infoBOList);
        session.getAsyncRemote().sendText(JSONObject.toJSONString(Result.defaultResult(ACTEnum.HAT_REPORT_LOCATION)));
    }

    /**
     * 获取所有信息
     */
    @Override
    public ConcurrentHashMap<String, List<HatHeartInfoBO>> getAllInfo() {
        return new ConcurrentHashMap<>(locationInfo);
    }

    /**
     * 根据设备ID删除
     */
    @Override
    public void removeInfo(String deviceId) {
        if (StringUtils.isNoneBlank(deviceId)) {
            locationInfo.remove(deviceId);
        }
    }

    /**
     * 获取设备ID
     */
    @Override
    public String getDeviceId(String message) {
        return transMessageToObject(message).getUserId();
    }

    /**
     * 根据当前行为判断是否可以被处理
     */
    @Override
    public boolean canHandle(String act) {
        return ACTEnum.HAT_REPORT_LOCATION.is(act);
    }


    @Override
    public Class<HatHeartInfoBO> getMessageClass() {
        return HatHeartInfoBO.class;
    }
}
    

